package com.jmu.bishe.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.jmu.bishe.entity.Member;
import com.jmu.bishe.service.HouseService;
import com.jmu.bishe.service.NewsService;
import com.jmu.bishe.service.UserService;
import com.jmu.bishe.service.main.TableService;
import com.jmu.bishe.utils.StringUtils;
import com.jmu.bishe.web.common.BaseController;

/**
 * 所有需要验证是否登录的都写在这里，url统计配置在根+ /admin/*
 * @author 
 *
 */
@Controller
public class AdminController extends BaseController{

	@Autowired
	private TableService tableService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private NewsService newsService;
	
	@Autowired
	private HouseService houseService;

	/**
	 * 用户注册页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/myhouse.do") 
    public String register(Model model,HttpServletRequest request) throws Exception {
        return "myefe";
    }
	
	/**
	 * 我的房源
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/my-house.do") 
    public String myHouse(Model model,HttpServletRequest request) throws Exception {
		//取得查询条件
        Map paramMap = houseService.getMyHouseParamMap(request,this.getCurUser(request));
        List params = (List)paramMap.get("tjs");
        String sql = (String)paramMap.get("sql");
     
        //取得参数
        String _currentPage = request.getParameter("currentPage");
        String _linePerPage = request.getParameter("linePerPage");
        int currentPage = _currentPage == null ? 1 : StringUtils.getStringToInt(_currentPage);
        int linePerPage = _linePerPage == null ? 10 : StringUtils.getStringToInt(_linePerPage);
        //获取查询列表
        List list = tableService.queryForList(sql, params,currentPage,linePerPage);
        
        model.addAttribute("list",list);
        //获取总页数
        int totalNumber = tableService.getTotalNumber(sql,params);
        //放参数
        int totalPage = totalNumber/linePerPage;
        model.addAttribute("totalPage",totalPage+1);
        model.addAttribute("linePerPage",linePerPage);
        model.addAttribute("currentPage",currentPage);
        Map requestParamMap = request.getParameterMap();
        Iterator iterator = requestParamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = StringUtils.getObjectToString(entry.getKey());
            String value = request.getParameter(key);
            if("keywords".equals(key)){
            	//这边注意，页面url get传参对中文 使用了encodeURI(encodeURI(keywords));所以我们要还原
            	try {
            		value = URLDecoder.decode(value,"utf-8");
        		} catch (UnsupportedEncodingException e) {
        			logger.info("中文参数编码失败！",e);
        		}
            }
            model.addAttribute(key,value);
        }
        return "my-house";
    }
	
	
	@RequestMapping(value="/admin/my-news.do") 
    public String myNews(Model model,HttpServletRequest request) throws Exception {
		//取得查询条件
        Map paramMap = newsService.getMyNewsParamMap(request,this.getCurUser(request));
        List params = (List)paramMap.get("tjs");
        String sql = (String)paramMap.get("sql");
     
        //取得参数
        String _currentPage = request.getParameter("currentPage");
        String _linePerPage = request.getParameter("linePerPage");
        int currentPage = _currentPage == null ? 1 : StringUtils.getStringToInt(_currentPage);
        int linePerPage = _linePerPage == null ? 10 : StringUtils.getStringToInt(_linePerPage);
        //获取查询列表
        List list = tableService.queryForList(sql, params,currentPage,linePerPage);
        
        model.addAttribute("list",list);
        //获取总页数
        int totalNumber = tableService.getTotalNumber(sql,params);
        //放参数
        int totalPage = totalNumber/linePerPage;
        model.addAttribute("totalPage",totalPage+1);
        model.addAttribute("linePerPage",linePerPage);
        model.addAttribute("currentPage",currentPage);
        Map requestParamMap = request.getParameterMap();
        Iterator iterator = requestParamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = StringUtils.getObjectToString(entry.getKey());
            String value = request.getParameter(key);
            if("keywords".equals(key)){
            	//这边注意，页面url get传参对中文 使用了encodeURI(encodeURI(keywords));所以我们要还原
            	try {
            		value = URLDecoder.decode(value,"utf-8");
        		} catch (UnsupportedEncodingException e) {
        			logger.info("中文参数编码失败！",e);
        		}
            }
            model.addAttribute(key,value);
        }
        return "my-news";
    }
	
	/**
	 * 删除新闻
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/delete-news.do") 
    public void deleteNews(Model model,HttpServletRequest request,HttpServletResponse response,String ids) throws Exception {
		JSONObject json = new JSONObject();
		try{
			//传入userId,保证只能删除自己的新闻
			newsService.deleteNews(ids,this.getCurUser(request).getUserId());
			json.put("message","删除成功！");
			json.put("action","reload");
		}catch (Exception e) {
			json.put("errorMsg","删除失败！");
		}
		printOut(response,json.toJSONString());
    }
	/**
	 * 删除房源
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/delete-house.do") 
    public void deleteHouse(Model model,HttpServletRequest request,HttpServletResponse response,String ids) throws Exception {
		JSONObject json = new JSONObject();
		try{
			//传入userId,保证只能删除自己的新闻
			houseService.deleteHouse(ids,this.getCurUser(request).getUserId());
			json.put("message","删除成功！");
			json.put("action","reload");
		}catch (Exception e) {
			json.put("errorMsg","删除失败！");
		}
		printOut(response,json.toJSONString());
    }
	
	/**
	 * 通过审核新闻
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/checked-news.do") 
    public void checkednews(Model model,HttpServletRequest request,HttpServletResponse response,String ids) throws Exception {
		JSONObject json = new JSONObject();
		try{
			if("0".equals(this.getCurUser(request).getRole())){
				//ids存nid
				newsService.checkedNews(ids);
				json.put("message","审核成功！");
				json.put("action","reload");
			}else{
				json.put("errorMsg","没有超级管理员权限！");
			}
		}catch (Exception e) {
			json.put("errorMsg","审核失败！");
		}
		printOut(response,json.toJSONString());
    }
	/**
	 * 通过房源审核
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/checked-house.do") 
    public void checkedhouse(Model model,HttpServletRequest request,HttpServletResponse response,String ids) throws Exception {
		JSONObject json = new JSONObject();
		try{
			if("0".equals(this.getCurUser(request).getRole())){
				//ids存hid
				houseService.checkedHouse(ids);
				json.put("message","审核成功！");
				json.put("action","reload");
			}else{
				json.put("errorMsg","没有超级管理员权限！");
			}
		}catch (Exception e) {
			json.put("errorMsg","审核失败！");
		}
		printOut(response,json.toJSONString());
    }
}
